//时间格式
const formatTime = date => {
  const time = new Date(date)
  const year = time.getFullYear()
  const month = time.getMonth() + 1
  const day = time.getDate()
  const hour = time.getHours()
  const minute = time.getMinutes()
  const second = time.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
//生成字符串时间格式
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//提示框
const toast = (type, title, duration) => {
  duration = duration ? duration : 2000
  const icons = {
    'error': '/static/images/icons/error.png',
    'warn': '/static/images/icons/warning.png',
  }
  if (type === 'success' || type === 'none') {
    const icon = type
    wx.showToast({
      icon,
      title,
      duration
    })
  } else {
    const image = icons[type]
    wx.showToast({
      image,
      title,
      duration
    })
  }
}
// 加载框
const loading = (title) => {
  wx.showLoading({
    title
  })
}

const randomId = () => {
  return Number(Math.random().toString().substr(3, 16) + Date.now()).toString(36);
}
const back = (time) => {
  setTimeout(() => {
    wx.navigateBack({
      delta: 1,
      duration: time
    })
  }, 1000)
}

const timeFormat = (time) => {
  if (time) {
    //时间戳转换成秒
    const seconds = Math.floor((+new Date() - new Date(time)) / 1000);
    if (seconds < 30) {
      return '刚刚';
    }
    const intervals = {
      年: 3600 * 24 * 365,
      月: 3600 * 24 * 30,
      周: 3600 * 24 * 7,
      天: 3600 * 24,
      小时: 3600,
      分钟: 60,
      秒: 1,
    };
    let counter = 0;
    for (const unitName in intervals) {
      if (intervals.hasOwnProperty(unitName)) {
        const unitVal = intervals[unitName];
        counter = Math.floor(seconds / unitVal);
        if (counter > 0) {
          return `${counter}${unitName}前`;
        }
      }
    }
  }
}

const getSimpleText = (html) => {
  var re1 = new RegExp("<.+?>", "g"); //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
  var msg = html.replace(re1, ''); //执行替换成空字符
  return msg;
}


module.exports = {
  formatTime,
  toast,
  loading,
  randomId,
  back,
  timeFormat,
  getSimpleText
}